import axios from 'axios'
import store from '@/store'
import { Loading } from 'element-ui'
const DEFAULT_LOADING = true
let showLoading
let loadingInstance = null
const service = axios.create({

  baseURL: 'http://192.168.96.86:1337/',

  timeout: 50000
})

service.interceptors.request.use(
  (config) => {
    // console.log(config)
    if (config.showLoading !== undefined) {
      showLoading = config.showLoading
    } else {
      showLoading = DEFAULT_LOADING
    }

    if (showLoading) {
      loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }
    const wirthPath = ['/auth/local', '/auth/local/register']
    // console.log(config.url)
    if (store.getters.token && !wirthPath.includes(config.url)) {
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  (response) => {
    const { data } = response
    if (loadingInstance) {
      loadingInstance.close()
    }
    return data
  },
  (error) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    return Promise.reject(error)
  }
)

export default service
